//the update function, if non-null, will be called per second
var update = null;
$(document).ready(function() {
	//TODO use onhashchange to support backward
	
	//initialize

	//represents current page in a single cat's homepage
	//if it's '', mean homepage
	var curPage = '';
	var curCat;//represents current cat
	//global DOM
	var back_to_home = $('#rpanel #back').hide();
	back_to_home.click(function() {
		homepage();
	});
	var lpanel = $('#lpanel');
	var rpanel = $('#rpanel');
	var llabel = $('#llabel');
	var content = $('#content-list');
	var manip = $('#maincontent #manip');

	var nav_template = {
		Home : 0,
		Track : 0,
		Photos : 0,
		Impressions : 0,
		Treat : 0
	};
	
	var nav = genNav().appendTo($('#rpanel')).hide();

	var main_title = $('<div class="main_title">' + 'NekoNeko Cat' + '</div>').appendTo(rpanel).hide();
	
	//go to homepage
	function homepage() {
		back_to_home.fadeOut();
		main_title.fadeIn();
		nav.fadeOut(function() {
			lpanel.delay(200).animate({
				height: '350px'
			}, function () {
				$('#content', lpanel).fadeIn();
			});
			rpanel.delay(200).animate({
				height: '340px'
			});
			llabel.animate({
				height: '40px'
			});
			curPage = '';
			llabel.empty();
			$('#lpanel #sec').text('Cats List');
			$('#maincontent .section').text('Events');

			var catpanel = $('#catpanel');
			if (catpanel) catpanel.fadeOut().remove();
			//cat-list
			var node = $('<ul id = "cats"></ul>').appendTo($('#cat-list').empty());
			//get cat-info
			$.getJSON('/catinfo/all', function(info_list) {
				for (var i = 0; i < info_list.length; ++i) {
					(function(t) {
					 	var li = $('<li/>').appendTo(node).click(function () { visitCat(t)});
						$('<div tabindex="0" class="catlink"><div><img src = "' + info_list[i].Portrait + '"></img></div>' + info_list[i].Name + '</div>').appendTo(li);
					 })(i);
				}
			});
			//content-list
			var display_elements = $('<div/>');
			var newest_time_stamp = null;
			$.getJSON('/newslist/all/', function(list){
				for(var i = 0; i < list.length; ++i) {
					genEventItem(list[i]).appendTo(display_elements);
					if (!newest_time_stamp)
						newest_time_stamp = list[i].Content.Time;
				}
				content.height('auto');
			});

			content.height(content.height());
			manip.fadeOut().empty().fadeIn();
			content.fadeOut(function() {
				content.empty();
				display_elements.appendTo(content);
				content.fadeIn();

				//set update function
				update = function() {
					$.getJSON(newest_time_stamp ? '/newslist/since/' + newest_time_stamp + '/all' : '/newslist/all/', function(newlist) {
						for (var i = 0; i < newlist.length; ++i) {
							genEventItem(newlist[i]).prependTo(display_elements).hide().show(100);
						}
						if (newlist.length > 0)
							newest_time_stamp = newlist[0].Content.Time;
					});
				};
			});
		});
	}

	homepage();

	function visitCat(c) {
		if (curPage == '') back_to_home.fadeIn();
		main_title.fadeOut();

		curCat = c;
		$('#lpanel #content').fadeOut(200, function() {
			//display cat info
			$.getJSON("/catinfo/" + c,function(info) {
				var cat_panel = $('<div id="catpanel"/>').appendTo($('#lpanel'));
				var info_panel = $('#llabel');

				$('<img src="' + info.Portrait + '"/>').appendTo(cat_panel);
				$('<div class="clear"/>').appendTo(cat_panel);
				$('<div class="name">' + info.Name + '</div>').appendTo(cat_panel);
				var loc_inf_display = $('<div/>').appendTo(info_panel);
				$.getJSON("/locationinfo/" + info.CurLocation, function(info) {
					$('<br><span class="sex">' + (info.Sex == 0 ? 'Lady' : 'Gentleman') + '</span><br>Last Position <span class="location">' + info.Location.Name + '</span>').appendTo(loc_inf_display);
					$('#tag', $(htmlLocationMap()).appendTo(loc_inf_display)).css({
						float:"left",
						"left": info.Location.X + 'px',
						"top": info.Location.Y + 'px',
						"background-color":"#fff",
						border:"1px solid #abc",
						position:"absolute",
						color: "#595F6D"
					});
					$('at Time:<span class="time">' + info.Time + '</span>').appendTo(loc_inf_display);
				});
			})
			.error(function(jqxhr, what, msg) {});
		});
		$('#lpanel').delay(200).animate({
			height: '150px'
		});
		rpanel.delay(200).animate({
			height: '140px'
		});
		$('#lpanel #sec').text('Cats' + c);
		$('#llabel').animate({
			height: '300px'
		});
		nav.delay(500).fadeIn();

		visitCatPage("Home");
	}

	function genNav() {
		//window.location.href = "#" + curPage;
		var c = "";
		var first = true;
		for (var p in nav_template) {
			if (first) first = false;
			else c += '<span class = "l">|</span>';

			c += '<span id = "' + p + '" class = "deactivated button" tabindex="0">  ' + p + '  </span>';
	}
		var navi = $('<div id = "nav"><h2 class = "section" >' + c + '</h2></div>');

		for (var p in nav_template) {
			(function(page) {
				$('#' + page, navi).click(function(){
					//window.location.href = '#' + page;
					visitCatPage(page);
				});
			}(p));
		}
		return navi;
	}
	function visitCatPage(page) {
		for (var p in nav_template) $('#' + p, nav).toggleClass('deactivated', true);
		$('#' + page, nav).toggleClass('deactivated', false);

		var newest_time_stamp = null;
		//content-list
		var display_elements = $('<div/>');
		switch(page) {
			case "Photos":
			{
				$.getJSON('/catalbum/bycat/' + curCat, function(list) {
					for(var i = 0; i < list.length; ++i)
						//list photos
						genPhotoEventItem(list[i]).appendTo(display_elements);
					content.height('auto');
				});
				update = null;
			}
			break;
			case "Impressions":
			{
				$.getJSON('/catimpression/bycat/' + curCat, function(list) {
					for(var i = 0; i < list.length; ++i)
						genImpressionEventItem(list[i]).appendTo(display_elements);
					content.height('auto');
				});
				update = null;
			}
			break;
			case "Treat":
			{
				$.getJSON('/cattreat/bycat/' + curCat, function(list) {
					for(var i = 0; i < list.length; ++i)
						genTreatEventItem(list[i]).appendTo(display_elements);
					content.height('auto');
				});
				update = null;
			}
			break;
			case "Track":
			{
				$.getJSON('/locationinfo/bycat/' + curCat, function(list) {
					for(var i = 0; i < list.length; ++i)
						genLocationEventItem(list[i]).appendTo(display_elements);
					content.height('auto');
				});
				update = null;
			}
			break;

			default:
			{
				$.getJSON('/newslist/bycat/' + curCat, function(list){
					for(var i = 0; i < list.length; ++i)
						genEventItem(list[i]).appendTo(display_elements);
					if (list.length > 0)
						newest_time_stamp = list[0].Content.Time;
					content.height('auto');
				});
				update = function() {
					$.getJSON(newest_time_stamp ? '/newslist/since/' + newest_time_stamp + '/bycat/' + curCat : '/newslist/bycat/' + curCat, function(newlist) {
						for (var i = 0; i < newlist.length; ++i) {
							genEventItem(newlist[i]).prependTo(display_elements).hide().show(100);
						}
						if (newlist.length > 0)
							newest_time_stamp = newlist[0].Content.Time;
					});
				};
			}
		}
		content.height(content.height())
		manip.fadeOut(function() {
			manip.empty();
			switch(page) {
				case "Impressions":
				$('<div class="button">Write Impression</div>').appendTo(manip).click(onWriteImpression);
				$('<div class="clear"/>').appendTo(manip);
				break;
				case "Photos":
				$('<div class="button">Submit Photos</div>').appendTo(manip).click(onSubmitPhoto);
				$('<div class="clear"/>').appendTo(manip);
				break;
			}
			manip.fadeIn();
		});
		content.fadeOut(curPage == '' ? 1000 : 100, function() {
			content.empty();
			//content-list
			switch(page) {
				case "Home":
				$('#maincontent .section').text('Events');
				break;
				default:
				$('#maincontent .section').text(page);
				break;
			}
			display_elements.appendTo(content);
			content.fadeIn();
		});

		curPage = page;
	}

	function genEventItemInternal(c, inner, time, title) {
		var title_html = ""
		if (title) title_html = "<h2 class = 'title'>" + title + "</h2><hr>";
		return $("<div class = 'item'/>").append(genEventLSection(c)).append($("<div class = 'right_sec'>" + title_html + "<div class = 'detail'>" + inner + "</div><div class = 'clear'/><hr><div class = 'time'>" + time + "</div>"));
	}

	function genEventLSection(c) {
		var ls = $("<div class = 'left_sec'></div>");
		$.getJSON("/catinfo/" + c, function(info) {
			$("<div><img src='" + info.Portrait + "'></img><div class = 'clear'/><span>" + info.Name + "</span></div>").appendTo(ls).click(function(){

				visitCat(c);
			});
		});
		return ls;
	}
	function genEventItem(e) {
		switch(e._type) {
			case 0:
			return genLocationEventItem(e.Content);
			case 1:
			return genTreatEventItem(e.Content);
			case 2:
			return genPhotoEventItem(e.Content);
			case 3:
			return genSayingEventItem(e.Content);
			case 4:
			return genImpressionEventItem(e.Content);
		}
	}
	function genPhotoEventItem(pe) {
		return genEventItemInternal(pe.Cat, '<img src="' + pe.URL+ '" class="photo"/><div class="clear"/><p>' + '\t' + 'Author: ' + htmlUser(pe.Author) + '</p>', pe.Time, 'photo');
	}
	function genLocationEventItem(le) {
		var node = genEventItemInternal(le.Cat, '<p>' + 'I\'m here:<span class="location">' + le.Location.Name+ '</span></p>' + htmlLocationMap() + '</div>', le.Time);
		$('#tag', node).css({
			float:"left",
			"left": le.Location.X + 'px',
			"top": le.Location.Y + 'px',
			"background-color":"#fff",
			border:"1px solid #abc",
			position:"absolute",
			color: "#595F6D"
		});
		return node;
	}
	function genTreatEventItem(te) {
		return genEventItemInternal(te.Cat, 'Treated by ' + htmlUser(te.Author), te.Time, 'Treat');
	}
	function genImpressionEventItem(ie) {
		return genEventItemInternal(ie.Cat, '<span class = "impression-name">' + ie.Content + '</span><br>' + 'commented by ' + htmlUser(ie.Author), ie.Time, 'Impression');
	}
	function genSayingEventItem(se) {
		return genEventItemInternal(se.Cat, '<p>' + se.Content + '</p>', se.Time, 'Says');
	}

	function htmlUser(user) {
		return '<span class="user" tabindex="0">' + user.Name + '</span>';
	}

	function wrapPost(json) {
		json.csrfmiddlewaretoken = $.cookie('csrftoken');
		return json;
	}
	onWriteImpression = function() {
		var writeDiv = $('#write-impression');
		if (!writeDiv || writeDiv.length == 0) {
			writeDiv = $('<div id="write-impression"><span class="desc">Put your impression here.</span><div/><textarea rows="2" cols="40" name="impression" id="input-impression" tabindex="0"></textarea><div/><button type="button" id="submit-impression">Submit</button></div>').appendTo(manip);
		
			$('#submit-impression', writeDiv)
			.click(function() {
				$.post('/post/catimpression/', wrapPost({
					catid:curCat,
					userid:0,
					content:$('#input-impression').val()
				}), function(data) {
					visitCatPage("Impressions");
				});
			});
			writeDiv.hide();
		}
		writeDiv.toggle(100);
	}
	onSubmitPhoto = function() {
		var sbtPhotoDiv = $('#submit-photo');
		if (sbtPhotoDiv.length == 0) {
			sbtPhotoDiv = $('<div id="submit-photo"><span class="desc">Snapshot!</span><div/><input type="file"><div/><button type="button" id="button-photo" tabindex="0">Submit</button></div>').appendTo(manip); 
			$('#button-photo', sbtPhotoDiv)
			.click(function() {
				alert('Sorry, unsupported now.');
				$.post('/post/catalbum/', wrapPost({
					catid:curCat,
					userid:0,
					content:$('#file').val()
				}), function(data) {
					visitCatPage("Photos");
				});
			});
			sbtPhotoDiv.hide();
		}
		sbtPhotoDiv.toggle(100);
	}
	setInterval("if (update != null) update();", 5000);
	function htmlLocationMap() { return '<div style="position:relative"><img src="../static/map.png" class="mapimg"><div id="tag">here</div>'; }
});
<!--
//-->
